import React, { Component } from 'react';

import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, Table } from 'antd';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import router from 'umi/router';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import PropTypes from 'prop-types';
import moment from 'moment';
import * as G from '../../../utils/common';

@connect((state: any) => ({
  orderMng: state.orderMng,
  loading: state.loading.effects['orderMng/postFetchPage'],
}))
class Page extends Component<any, any> {
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      brand: [],
      series: [],
      type: [],
      dealer: [],
      judgeData: [],
      extendStatus: false,
      formValues: {},
      pagination: {
        current: 1,
        pageSize: 10,
      },
      goodsTypeOptions:[],
    };
  }

  // 重置品牌
  setBrand = () => {
    this.searchForm.current.resetFields(['brandId', 'carSeries',]);
    this.props.dispatch({
      type: 'orderMng/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: e => {
        this.setState({
          brand: e.data.map(e => ({
            label: e.brandName,
            value: e.brandCode,
          })),
          series: [],
          type: [],
          dealer: [],
        });
      },
    });
  };

  // 重置车系
  setSeries = () => {
    this.searchForm.current.resetFields(['carSeries', ]);

    this.setState({ series: [], type: [] });
    const brandId = this.searchForm.current.getFieldValue('brandId');
    brandId &&
      this.props.dispatch({
        type: 'orderMng/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId,
        },
        callback: e => {
          this.setState({
            series: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  };
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;
    this.setBrand();
    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location;
      let values = {
        ...pagination
      };
      if ( sourcePage === 'orderMng' ) {
        //  详情返回
        const tempValues = sessionStorage.getItem('orderMngSearchValues')
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {})
        };
        this.setState({
          extendStatus: true,
        })
      }
      const { current, pageSize, ...rest } = values;
      this.setState({
        formValues: {
          ...formValues,
          ...rest,
        },
        pagination: {
          current,
          pageSize
        }
      }, () => {
        const { formValues, pagination } = this.state
        this.searchForm.current.setFieldsValue({
          ...formValues,
        });
        dispatch({
          type: 'orderMng/postFetchPage',
          payload: { url: '/msneworder/order/list/search', ...formValues, ...pagination },
        });
      })
    })
    this.setBrand();
    this.getGoodsType();
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderMng/initData',
    });
  }
  //获取商品类型新阿拉数据
  getGoodsType=()=>{
    this.props.dispatch({
      type: 'orderMng/getDataWithRes',
      payload: { url: '/optshop/base/goodstype/query/drop/list',},
      callback: (res:any) => {
        this.setState({ 
          goodsTypeOptions: res?.data?.list?.map((item:any)=>{
            return {
              label: item.goodsTypeName,
              value: item.goodsTypeId
            }
           }),
        });
       }
    })
  }
  handleFormReset = (fields: any) => {
    this.searchForm.current.setFieldsValue({})
    this.setState({
      formValues: {},
      pagination: {
        current: 1,
        pageSize: 10,
      },
    });
  }

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    const params = {
      ...formValues,
      current, 
      pageSize,
      ...filters,
    };
    this.setState({
      pagination: {
        current, 
        pageSize,
      }
    }, () => {
      dispatch({
        type: 'orderMng/postFetchPage',
        payload: { url: '/msneworder/order/list/search', ...params },
      });
    })
  }
  dataFormat = (fields: any) => {
    const { pagination } = this.state;
    if (G.isNotEmptyAndNil(fields['createDateRange'])) {
      const [start, end] = fields.createDateRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD');
      fields['endTime'] = moment(end).format('YYYY-MM-DD');
      delete fields['createDateRange'];
    }
    return {
        ...fields,
        ...pagination,
      };
  };
  //点击商品名称跳转到商品详情页
  handleDetail=(record:any)=>{
    sessionStorage.setItem('spuId', JSON.stringify(record.spuId || ''));
    const { formValues, pagination } = this.state;
    const searchValues = {
      ...formValues,
      ...pagination
    };
    sessionStorage.setItem('orderMngSearchValues', JSON.stringify(searchValues));
    router.push({pathname:'/goodsManager/goodsMng/goodDetail',query:{data:'orderMng'}});
  }

  render() {
    const {
      orderMng: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { brand, series, extendStatus,goodsTypeOptions } = this.state;
    const orderChannelOptions = getDictOptionsByCode(this.context.dicData, 'orderChannel');
    const orderStatusOptions = getDictOptionsByCode(this.context.dicData, 'orderStatus');
    const searchItems = [
      {
        type: 'select',
        title: `品牌`,
        key: 'brandId',
        selectOptions: brand,
        onChange: () => {
          this.setSeries();
        },
      },
      {
        type: 'select',
        title: `车系`,
        key: 'carSeries',
        selectOptions: series,
      },
    {
      type: 'input',
      title: `订单编号`,
      key: 'shopOrderNo',
      maxLength: 20,
    },
    {
      type: 'select',
      title: `商品类型`,
      key: 'goodsTypeId',
      selectOptions: goodsTypeOptions,
    },
    {
      type: 'select',
      title: `订单状态`,
      key: 'orderStatus',
      selectOptions: orderStatusOptions,
    },
    {
      type: 'select',
      title: `订单来源`,
      key: 'orderChannel',
      selectOptions: orderChannelOptions,
    },
    {
      type: 'input',
      title: `VIN码`,
      key: 'vin',
      maxLength: 20,
      customStyle: 8,
    },
    {
      type: 'rangePicker',
      title: `创建日期`,
      key: 'createDateRange',
      customStyle: 8,
      showTime: false,
      format: 'YYYY-MM-DD',
    },
  ];

  const columns = [
      {
        title: `品牌`,
        dataIndex: 'brandName',
      },
      {
        title: `车系`,
        dataIndex: 'carSeries',
      },
    {
      title: `VIN码`,
      dataIndex: 'vin',
    },
      {
        title: `父级订单编号`,
        dataIndex: 'parentOrderNo',//详细设计中没找到对应参数
      },
    {
      title: `商品订单编号`,
      dataIndex: 'shopOrderNo',
    },
    {
      title: `第三方订单编号`,
      dataIndex: 'thirdOrderNo',
    },
    {
      title: `商品类型`,
      dataIndex: 'goodsTypeName',
    },
    {
      title: `订单来源`,
      dataIndex: 'orderChannel',
      render: text => {
        if (text == null) {
          return '';
        }
        return getDicByKey(this.context.dicData, `orderChannel`, text + '');
      },
    },
    {
      title: `商品编号`,
      dataIndex: 'goodsId',//多规格展示商品编码:goodsId，单规格展示商品编码:spuId
      render: (text:any, record:any)=>{
        if(record.goodsSpecFlag == 1){
          //单规格
          return record.spuId;
        }else if(record.goodsSpecFlag == 2){//多规格
          return record.goodsId;
        }else{
          return ''
        }
       }
    },
    {
      title: `商品名称`,
      dataIndex: 'goodsName',
      render: (text:any, record:any)=>{
       return <a onClick={() => this.handleDetail(record)}>{text}</a>;
       }
    },
    {
      title: `商品原价（元）`,
      dataIndex: 'goodsPrice',
    },
    {
      title: `商品折扣价（元）`,
      dataIndex: 'discountPrice',
    },
    {
      title: `商品成交价`,
      dataIndex: 'tradePrice',
    },
    {
      title: `商品数量`,
      dataIndex: 'quantity',
    },
    {
      title: `支付方式`,
      dataIndex: 'firstPayType',
      render: (text:any,record:any) => {
          if(text == 55){
            return '工行支付'
          }else if(text == 1){
            return '微信二维码'
          }else if(text == 4){
            return '支付宝二维码'
          }else if(text == 9){
            return '微信、支付宝二维码'
          }else{
            return text
          }
      }
    },
    {
      title: `订单总金额（元）`,
      dataIndex: 'totalAmount',
    },
    {
      title: `订单状态`,
      dataIndex: 'orderStatus',
      render: text => {
        if (text == null) {
          return '';
        }
        return getDicByKey(this.context.dicData, `orderStatus`, text + '');
      },
    },
    {
      title: `失效原因`,
      dataIndex: 'orderInvalidReason',
    },
    {
      title: `第三方支付状态`,
      dataIndex: 'thirdOrderStatus',
      render: text => {
        if (text == 0) {
          return '待支付';
        }else if(text == 1){
          return '已支付'
        }else if(text == 2){
          return '支付失败'
        }else{
          return ''
        }
      },
    },
    {
      title: `创建时间`,
      dataIndex: 'createTime',
    },
    {
      title: `下单用户`,
      dataIndex: 'userPhone',
    },
    
  ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{
              type: 'orderMng/postFetchPage',
              url: '/msneworder/order/list/search',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
        <Table
            size={'small'}
            rowKey={record => record.id}
            dataSource={ list || [] }
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
      </div>
    );
  }
}

export default Page;
